package mysql

import (
	"fmt"
	"github.com/go-xorm/xorm"
	"io"
	"os"
	"path/filepath"
	"strconv"
	"strings"
)

var tableHeaderTemplate = `
| 序号 | 字段名称 | 类型 | 主键 | 允许空值 | 默认 | 备注 |
| :--: |    --   |  --  | :--: |  :--:   |  --  |  --  |
`

func ExportMarkdown(engine *xorm.Engine, outputPath string) {
	err := createIfNotExists(outputPath, false)
	if err != nil {
		panic(err)
	}
	tables, err := engine.DBMetas()
	if err != nil {
		panic(err)
	}
	if len(tables) == 0 {
		panic("没有发现表")
	}
	for _tindex, t := range tables {
		tableDesc := "### " + strconv.Itoa(_tindex+1) + "、" + t.Comment + "—" + t.Name + "\n"
		tableContent := tableHeaderTemplate
		for _index, c := range t.Columns() {
			pk := ""
			nullable := ""
			if c.IsPrimaryKey {
				pk = "√"
			}
			if c.Nullable {
				nullable = "√"
			}
			tableContent +=  fmt.Sprintf(
				"| %d | `%s` | %s | %s | %s | %s | %s |\n",
				_index + 1,
				c.Name,
				c.SQLType.Name + "(" + strconv.Itoa(c.SQLType.DefaultLength) + ")",
				pk,
				nullable,
				c.Default,
				strings.ReplaceAll(strings.ReplaceAll(c.Comment,"|","\\|"), "\n", ""),
			)
		}
		err := writeFile(outputPath, []byte(tableDesc + tableContent), os.ModePerm)
		if err != nil {
			fmt.Errorf("save table to markdown file error: %s", err.Error())
		}
	}
}

func createIfNotExists(path string, isDir bool) error {
	if _, err := os.Stat(path); err != nil {
		if os.IsNotExist(err) {
			if isDir {
				return os.MkdirAll(path, 0755)
			}
			if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
				return err
			}
			f, err := os.OpenFile(path, os.O_CREATE, 0755)
			if err != nil {
				return err
			}
			f.Close()
		}
	}
	return nil
}
func writeFile(filename string, data []byte, perm os.FileMode) error {
	f, err := os.OpenFile(filename, os.O_RDWR | os.O_CREATE | os.O_APPEND, perm)
	if err != nil {
		return err
	}
	n, err := f.Write(data)
	if err == nil && n < len(data) {
		err = io.ErrShortWrite
	}
	if err1 := f.Close(); err == nil {
		err = err1
	}
	return err
}